
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Linq.Extensions;
using Abp.Organizations;
using JYJ.AiYard.StationManagement.TbClientRegisters;
using JYJ.AiYard.StationManagement.TbClientRegisters.Dtos;
using JYJ.AiYard.StationManagement.TbClientRegisters.DomainService;
using JYJ.AiYard.StationManagement.TbClientRegisters.Authorization;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbClientRegisters
{
    /// <summary>
    /// TbClientRegister应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbClientRegisterAppService : AiYardAppServiceBase, ITbClientRegisterAppService
    {
        private readonly IRepository<TbClientRegister, long> _entityRepository;

        private readonly ITbClientRegisterManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard; 


        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbClientRegisterAppService(
        IRepository<TbClientRegister, long> entityRepository,
        ITbClientRegisterManager entityManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard  
        )
        {
            _entityRepository = entityRepository; 
            _entityManager=entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }

        /// <summary>
        /// 获取当前用户组织单元下的所有客户端信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<TbClientRegisterListDto>> GetAllTbClient(long StationId)
        {
            long Station_Id = StationId; 
            var tbDepart = await _entityRepository.GetAll().Where(o => o.Station_ID == Station_Id).ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<TbClientRegisterListDto>>();   

            return allTbDepart;
        }


        /// <summary>
        /// 获取TbClientRegister的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbClientRegisterPermissions.Query)] 
        public async Task<PagedResultDto<TbClientRegisterListDto>> GetPaged(GetTbClientRegistersInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId==null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
            var query1 = _aiYardDbTableIssuedCard.GetTbClientRegister(StationList, filterText.FilterText);

            var query = query1.AsQueryable();
            var count = query.Count();

            //var count = await query.CountAsync();

            var entityList = query
                .OrderBy(input.Sorting).AsNoTracking()
                .PageBy(input)
                .ToList();

            // var entityListDtos = ObjectMapper.Map<List<TbClientRegisterListDto>>(entityList);
            var entityListDtos =entityList.MapTo<List<TbClientRegisterListDto>>();

			return new PagedResultDto<TbClientRegisterListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TbClientRegisterListDto信息
		/// </summary>
		[AbpAuthorize(TbClientRegisterPermissions.Query)] 
		public async Task<TbClientRegisterListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbClientRegisterListDto>();
		}

		/// <summary>
		/// 获取编辑 TbClientRegister
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbClientRegisterPermissions.Create,TbClientRegisterPermissions.Edit)]
		public async Task<GetTbClientRegisterForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbClientRegisterForEditOutput();
            TbClientRegisterEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbClientRegisterEditDto>();

			}
			else
			{
				editDto = new TbClientRegisterEditDto();
			}

			output.TbClientRegister = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbClientRegister的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbClientRegisterPermissions.Create, TbClientRegisterPermissions.Edit)]
		public async Task<Dictionary<string, string>> CreateOrUpdate(CreateOrUpdateTbClientRegisterInput input)
		{
			Dictionary<string, string> result = new Dictionary<string, string>();
			if (input.TbClientRegister.Station_ID <= 0)
			{
				result.Add("retype", "-1");
				result.Add("revalue", "请选择确定的场所名称");
				return result;
			}
			if (input.TbClientRegister.Id.HasValue)
			{
				return await Update(input.TbClientRegister);
			}
			else
			{
				return await Create(input.TbClientRegister);
			}
		}


		/// <summary>
		/// 新增TbClientRegister
		/// </summary>
		[AbpAuthorize(TbClientRegisterPermissions.Create)]
		protected virtual async Task<Dictionary<string, string>> Create(TbClientRegisterEditDto input)
		{
			Dictionary<string, string> result = new Dictionary<string, string>(); 
			//TODO:新增前的逻辑判断，是否允许新增
			if (_entityRepository.GetAll().Where(o => o.Client_ID == input.Client_ID).Count() > 0)
            {
				result.Add("retype", "-1");
				result.Add("revalue", "此客户端标识已经存在，请修改客户端标识!"); 
            }
            else if (_entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID && o.Client_Stop == false && (o.Client_Type == "上传岗亭一体" || o.Client_Type == "上传电脑")).Count() > 0
                && (input.Client_Type== "上传岗亭一体" || input.Client_Type == "上传电脑")
                && input.Client_Stop == false)
            {
				result.Add("retype", "-1");
				result.Add("revalue", "已经注册了一台上传电脑不允许再注册为上传电脑!"); 
			}
            
            var entity=input.MapTo<TbClientRegister>();
			

			entity = await _entityRepository.InsertAsync(entity);
			if (result.Count <= 0)
			{
				result.Add("retype", "1");
				result.Add("revalue", "注册客户端成功");
			}
			return result;
		}

		/// <summary>
		/// 编辑TbClientRegister
		/// </summary>
		[AbpAuthorize(TbClientRegisterPermissions.Edit)]
		protected virtual async Task<Dictionary<string,string>> Update(TbClientRegisterEditDto input)
		{
			Dictionary<string, string> result = new Dictionary<string, string>();
			
			if (_entityRepository.GetAll().Where(o => o.Client_ID == input.Client_ID && o.Id!=input.Id ).Count() > 0)
            {
				result.Add("retype", "-1");
				result.Add("revalue", "此客户端标识已经存在，请修改客户端标识!"); 
            }
            else if (_entityRepository.GetAll().Where(o => o.Station_ID == input.Station_ID && o.Client_Stop == false && o.Id != input.Id && (o.Client_Type == "上传岗亭一体" || o.Client_Type == "上传电脑")).Count() > 0
                && (input.Client_Type == "上传岗亭一体" || input.Client_Type == "上传电脑")
                && input.Client_Stop==false)
            {
				result.Add("retype", "-1");
				result.Add("revalue", "已经注册了一台上传电脑不允许再注册为上传电脑!"); 
            }
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
			if (result.Count <= 0)
			{
				result.Add("retype", "1");
				result.Add("revalue", "更新客户端注册信息成功");
			}
			return result;
		}



		/// <summary>
		/// 删除TbClientRegister信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbClientRegisterPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
            if (_aiYardDbTableIssuedCard.CheckIsForeignKey(input.Id,0,"Client"))
            {
                throw new Exception(input.Id + "存在外键约束，不允许删除");
            }
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbClientRegister的方法
		/// </summary>
		[AbpAuthorize(TbClientRegisterPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
            foreach (long Id in input)
            {
                if (_aiYardDbTableIssuedCard.CheckIsForeignKey(Id, 0, "Client"))
                {
                    throw new Exception(Id + "存在外键约束，不允许删除");
                }
            }
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出TbClientRegister为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


